package com.forum.model.dao;

import java.util.List;

import org.hibernate.Session;

import com.forum.model.pojo.Post;
import com.forum.model.util.SessionManager;

public class PostDAO implements GenericDAO<Post, Long> {

	private Session session;

	@Override
	public boolean insert(Post post) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.save(post);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public boolean update(Post post) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.update(post);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public boolean delete(Post post) {
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			session.delete(post);
			session.getTransaction().commit();

			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return false;
	}

	@Override
	public Post getObjectById(Long id) {
		Post post = null;
		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			post = (Post) session.get(Post.class, id);
			session.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}
		return post;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Post> getAll() {
		List<Post> all = null;

		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			all = (List<Post>) session.createQuery("from Post").list();
			session.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}

		return all;
	}

	@SuppressWarnings("unchecked")
	public List<Post> getAll(long topicId) {
		List<Post> all = null;

		try {
			session = SessionManager.getSessionFactory().openSession();
			session.beginTransaction();
			all = (List<Post>) session.createQuery(
					"from Post where topic = " + topicId).list();

			ForumUserDAO fDao = new ForumUserDAO();

			for (Post p : all) {
				p.setPoster(fDao.getObjectById(p.getPostOwner()));
			}
			session.getTransaction().commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			SessionManager.closeSession(session);
		}

		return all;
	}
}
